#!/usr/bin/env python

import urllib
import lxml.etree
import sys
import time
from rdf import *

ARPAURL = "http://demo.seco.tkk.fi/arpa/"

def assign_terms(text, project, amount=10, threshold=None):
  params = {'project': project,
            'text': text.encode('UTF-8'),
            'amount': amount}
  if threshold: params['threshold'] = threshold

  data = urllib.urlencode(params)
  
  attempt = 1
  while True:
    try:
      res = urllib.urlopen(ARPAURL, data=data)
    except IOError as e:
      print >>sys.stderr, "Error accessing Arpa (HTTP access for URL %s failed: %s). Trying again. Attempt: %d" % (ARPAURL, str(e), attempt)
      attempt += 1
      time.sleep(2)
      
      if attempt > 5:
        print >>sys.stderr, "Accessing Arpa failed. Giving up."
        raise
      
      continue
    
    try:
      tree = lxml.etree.parse(res)
      break
    except Exception as e:
      print >>sys.stderr, "ARPA result parsing failed. Trying again. Attempt:", attempt
      attempt += 1
      
      if attempt > 5:
        print >>sys.stderr, "ARPA result parsing failed. Giving up."
        raise

    res.close()
  
  uris = []
  for element in tree.getroot().iter("uri"):
    uris.append(URIRef(element.text))
  return uris
  
if __name__ == '__main__':
  print assign_terms('kettu juoksi lammen yli kana suussaan', "poi")

